<?php
class IndexController extends Controller {

    protected function _init(){
        header("Content-Type:text/html; charset=utf-8");
    }
    private function ajaxReturn($data){
        echo json_encode($data);
        exit;
    }
    public function IndexAction(){
        if($_COOKIE['pwd'] !== 'admin'){
            $this->display('Login');
        }else{
            $this->display();
        }
    }
    public function DataAction(){
        $Model = M();
        $era = $Model->query("SELECT * FROM `timeline` WHERE `type` = 2 AND `status` = 1 ORDER BY `id` DESC");
        $headline = $Model->query("SELECT * FROM `timeline` WHERE `type` = 3 AND `status` = 1 ORDER BY `id` DESC LIMIT 1");
        $list = $Model->query("SELECT * FROM `timeline` WHERE `type` = 1 AND `status` = 1 ORDER BY `id` DESC");
        $ret = array('timeline' => array(
                'headline' => $headline[0]['headline'],
                'type' => 'default',
                'text' => htmlspecialchars_decode($headline[0]['text']),
                'asset' => json_decode($headline[0]['asset']),
                'era' => array(),
                'date' => array(),
            ));
        foreach ($list as $v) {
            $ret['timeline']['date'][] = $this->convert($v);
        }
        foreach ($era as $v) {
            $ret['timeline']['era'][] = $this->convert($v);
        }
        $this->ajaxReturn($ret);
    }
    private function convert($data){
        $ret = array(
            'headline' => $data['headline'],
            'startDate' => date('Y,n,d,H,i,s', strtotime($data['startDate'])),
            'text' => htmlspecialchars_decode($data['text']),
            'asset' => json_decode($data['asset']),
            );
        if(strtotime($data['endDate']) > 0){
            $ret['endDate'] = date('Y,n,d,H,i,s', strtotime($data['endDate']));
        }
        if($data['tag'] != ''){
            $ret['tag'] = $data['tag'];
        }
        return $ret;
    }
}
